<template>
	<view>
		<view class="flex justify-end padding" style="padding-bottom: 40px;">
			<view class="addworkfunction_btn">
				<button class="bg-green" size="mini"  @click="confirFun">确定</button>
			</view>
		</view>
		<ot-input-tags class="bg-white" @change="change" :selectlist='selectlist' :placeholder='placeholder'></ot-input-tags>
		<view class="margin-top margin-left">备选标签</view>
		<view class="padding-sm flex flex-wrap">
			<view class="padding-xs" v-for="(item,index) in taglibs" :key="index" >
				<view class='cu-tag round bg-white shadow' :class="'text-' + item.color" @click="selectTag(item)">{{item.title}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		props:{
			//已选标签，字符串, e.g. '朋友、亲人'
			selectTagsString:{
				type:String,
				default(){
					return ""
				}
			},
			//标签间隔符
			gap:{
				type:String,
				default(){
					return "、"
				}
			},
			//已选标签，字符串数组, e.g. ['朋友','亲人']
			selectTags:{
				type:Array,
				default(){
					return []
				}
			},
			placeholder:{
				type:String,
				default(){
					return '请输入标签，以空格结束'
				}
			},
			//备选标签名称集合,字符串数组，e.g. ['朋友','亲人']
			origTags:{
				type:Array,
				default(){
					return []
				}
			},
		},
		data() {
			return {
				selectlist:[]
			}
		},
		computed:{
			taglibs(){
				let result = []
				if(this.origTags.length){
					let _that = this
					let selecttags = this.selectlist.map(e=>e.title)
					this.origTags.forEach(e=>{
						if(selecttags.includes(e)){
							result.push({
								title:e,
								color:'green'
							})
						}else{
							result.push({
								title:e,
								color:'black'
							})
						}
					})
				}
				return result
			}
		},
		watch:{
			selectTagsString(newValue){
				this.selectlist = newValue.split(_that.gap).map(e=>{
					return {title:e}
				})
				
			},
			selectTags(newValue){
				this.selectlist = newValue.map(e=>{
					return {title:e}
				})
			}
		},
		methods: {
			change(arr){
				this.selectlist = JSON.parse(JSON.stringify(arr));
			},
			selectTag(item){
				let selecttags = this.selectlist.map(e=>e.title)
				if(selecttags.includes(item.title)){
					let index = selecttags.indexOf(item.title)
					this.selectlist.splice(index,1)
				} else {
					this.selectlist.push(item)
				}
			},
			confirFun() {
				let value = this.selectlist.map(e=>e.title).join(this.gap)
				this.$emit("confirm",{tags:value})
			}
		}
	}
</script>

<style>
.addworkfunction_btn{
	position: absolute;
	right: 5px;
	z-index: 10;
}
</style>
